<template>
  <div class="login">
    <el-form :model="loginForm" status-icon class="container" :rules="myrules" ref="loginRef">
      <el-form-item>
        <div class="avatar">
          <img src="../assets/wan.jpg" alt="">
        </div>
      </el-form-item>
      <el-form-item prop="usernmae">
        <el-input  v-model="loginForm.username" autocomplete="off" prefix-icon="myicon myicon-user" ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="loginForm.password" autocomplete="off" prefix-icon="myicon myicon-key" @keydown.enter.native="handLogin"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-btn" @click="handLogin('loginRef')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>

import { login } from '@/api'

export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      myrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handLogin (rename) {
      this.$refs[rename].validate((isPass) => {
        if (isPass) {
          login({ username: this.loginForm.username, password: this.loginForm.password })
            .then(res => {
              if (res.meta.status === 200) {
                // 保存token到本地数据
                localStorage.setItem('mytoken', res.data.token)
                // 保存username到本地数据:
                localStorage.setItem('username', res.data.username)
                this.$router.push({ name: 'home' })
              } else {
                this.$message.error(res.meta.msg)
              }
            })
        } else {
          console.log('登陆失败')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/login.scss";
</style>
